package br.com.goals.tableedit.util;

import org.apache.log4j.Logger;

import br.com.goals.tableedit.model.FieldConfig;
import br.com.goals.tableedit.model.HtmlSelectOption;
import br.com.goals.tableedit.model.ReplaceString;

/**
 * Cria o cod do Campo do formulario
 * 
 * @author Fabio Issamu Oshiro
 * 
 */
public class FormFieldFactory {
	private static Logger logger = Logger.getLogger(FormFieldFactory.class);
	private static final String DOJO_DATEPICKER = "<script type=\"text/javascript\"><!--\n"
		+ "dojo.require(\"dojo.widget.DatePicker\");" 
		+ "document.write('<div dojoType=\"dropdowndatepicker\" id=\"{id}\" value=\"{valor}\" name=\"dojo.{id}\" inputName=\"{id}\" displayFormat=\"dd/MM/yyyy\" containerToggle=\"wipe\" containerToggleDuration=\"300\" saveFormat=\"rfc\"></div>')"
		+ "\n//--></script>"
		+ "<noscript><p><input type=\"text\" id=\"{id}\" name=\"{id}\" value=\"{valorLocalizado}\" onkeyup=\"formatX('##/##/####',this)\" {editable}/></p></noscript>";
		;
	
	public static String createHidden(FieldConfig fieldConfig, String value) {
		return "<input type=\"hidden\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" />";
	}
	private static String createOptions(FieldConfig fieldConfig, String value) {
		StringBuilder retorno = new StringBuilder();
		try {
			for (HtmlSelectOption option : fieldConfig.htmlSelect.getOptions()) {
				String selected = "";
				/*
				 * marcar o valor igual
				 */
				if (option != null && value != null && value.equals(option.value)) {
					selected = "selected=\"selected\"";
				}
				retorno.append("<option value=\"" + option.value + "\" " + selected + ">");
				retorno.append(option.label);
				retorno.append("</option>\n");
			}
		} catch (Exception e) {
			System.out.println("FormFieldFactory.createOptions() -> Error while creating options...");
			e.printStackTrace();
		}
		return retorno.toString();
	}

	public static String createComboWithNull(FieldConfig fieldConfig, String value, String nullLabel) {
		// System.out.println("createCombo()");
		StringBuilder retorno = new StringBuilder();
		String editable = "";
		if (!fieldConfig.isEditable) {
			editable = " disabled=\"disabled\"";
		}
		retorno.append("<select id=\"")
			.append(fieldConfig.htmlName)
			.append("\" name=\"")
			.append(fieldConfig.htmlName)
			.append("\"")
			.append(editable);
		if(fieldConfig.htmlSelect.size!=0){
			retorno.append(" size=\"")
				.append(fieldConfig.htmlSelect.size)
				.append("\"");
		}
		retorno.append(" >\n");
	
		retorno.append("<option value=\"\">" + nullLabel + "</option>");
		retorno.append(createOptions(fieldConfig, value));
		retorno.append("</select>\n");
		return retorno.toString();
	}

	public static String createCombo(FieldConfig fieldConfig, String value) {
		// System.out.println("createCombo()");
		StringBuilder retorno = new StringBuilder();
		String editable = "";
		if (!fieldConfig.isEditable) {
			editable = " disabled=\"disabled\"";
		}
		
		retorno.append("<select id=\"");
		if(fieldConfig.htmlId!=null){
			retorno.append(fieldConfig.htmlId);
		}else{
			retorno.append(fieldConfig.htmlName);
		}
		retorno.append("\" name=\"")
			.append(fieldConfig.htmlName)
			.append("\"")
			.append(editable);
		if(fieldConfig.htmlSelect.size!=0){
			retorno.append(" size=\"")
				.append(fieldConfig.htmlSelect.size)
				.append("\"");
		}
		retorno.append(" >\n");
		retorno.append(createOptions(fieldConfig, value));
		retorno.append("</select>\n");
		return retorno.toString();
	}

	public static String createEditable(FieldConfig fieldConfig, String value) {
		// System.out.println("fieldConfig.className="+fieldConfig.className);
		String editable = "";
		if (!fieldConfig.isEditable) {
			String retorno="";
			if (fieldConfig.className.equals("java.lang.Boolean")) {
				retorno = createHidden(fieldConfig,value);
				if(value!=null && (value.equals("true") || value.equals("1"))){
					value = "Sim";
				}else{
					value = "N&atilde;o";
				}
			} else if (fieldConfig.className.equals("java.lang.String")) {
				value = Conversor.HTMLEntityEncode(value+"");
				retorno = createHidden(fieldConfig,value);
			} else if (fieldConfig.htmlSelect != null) {
				for(HtmlSelectOption s:fieldConfig.htmlSelect.getOptions()){
					if(s.value.equals(value)){
						value = Conversor.HTMLEntityEncode(s.label+"");
						break;
					}
				}
			}
			if(value!=null){
				for(ReplaceString rep:fieldConfig.getListReplaceDisplayString()){
					if(value.equals(rep.getSearch())){
						value=rep.getNewValue();
					}
				}
			}
			return retorno +"<div class=\"info\">"+ value +"</div>";
		}
		if (fieldConfig.htmlSelect != null) {
			// System.out.println("call createCombo()");
			// criar um combo
			if (fieldConfig.isNullable) {
				return createComboWithNull(fieldConfig, value, "");
			} else {
				return createCombo(fieldConfig, value);
			}
		} else if (fieldConfig.className.equals("java.lang.String")) {
			if(value==null)value="";
			//value = Conversor.HTMLEntityEncode(value+"");
			if (fieldConfig.displaySize > 300) {
				if(fieldConfig.rtf){//Alterando para RTE
					//return "<script type=\"text/javascript\"><!--\ncriaRTE(\""+fieldConfig.htmlName+"\",\""+value.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r","\\r").replace("<script","<sc\"+\"ript").replace("</script","</sc\"+\"ript")+"\");//--></script><noscript><div><textarea id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" cols=\"40\" rows=\"10\" " + editable + ">" + Conversor.HTMLEntityEncode(value) + "</textarea></div></noscript>";
					
					//Trocado para o TinyMCE
					logger.debug("criando o TinyMCE via seletor");
					return "<textarea id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" " + editable + " class=\"mceEditor\" rows=\"10\" cols=\"40\">" + Conversor.HTMLEntityEncode(value) + "</textarea>";
				}else{
					return "<textarea id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" " + editable + " rows=\"10\" cols=\"40\">" + Conversor.HTMLEntityEncode(value) + "</textarea>";
				}
			} else {
				value = Conversor.HTMLEntityEncode(value);
				return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" maxlength=\"" + fieldConfig.displaySize + "\" " + editable + " /> <span class=\"help\">"+fieldConfig.help+"</span>";
			}
		} else if (fieldConfig.className.equals("java.lang.Integer")) {

			return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" " + editable + "/>";
		} else if (fieldConfig.className.equals("java.lang.Float")) {
			return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" " + editable + "/>";
		} else if (fieldConfig.className.equals("java.lang.Double")) {
			return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" " + editable + "/>";
		} else if (fieldConfig.className.equals("java.sql.Timestamp")) {
			return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" " + editable + "/>";
		} else if (fieldConfig.className.equals("java.sql.Date")) {
			if (value == null) {
				value = "1988-02-01";
			}
			return DOJO_DATEPICKER
				.replace("{id}", fieldConfig.htmlName)
				.replace("{valor}",value.toString())
				.replace("{valorLocalizado}",Conversor.deYYYYMMDDparaDDMMYYYY(value.toString()))
				.replace("{editable}", editable)
				+"<span class=\"help\">"+fieldConfig.help+"</span>"
				;
			//return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + Conversor.deYYYYMMDDparaDDMMYYYY(value.toString()) + "\" onkeyup=\"formatX('##/##/####',this)\" " + editable + "/>";
		} else if (fieldConfig.className.equals("java.math.BigDecimal")) {
			return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" " + editable + "/>";
		} else if (fieldConfig.className.equals("java.lang.Boolean")) {
			String checked = "";
			if (value != null && (value.equals("true") || value.equals("1"))) {
				checked = "checked=\"checked\"";
			}
			return "<input type=\"checkbox\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"1\" " + checked + " class=\"chk\" " + editable + "/>";
		} else if (fieldConfig.className.equals("java.lang.Long")) {
			return "<input type=\"text\" id=\"" + fieldConfig.htmlName + "\" name=\"" + fieldConfig.htmlName + "\" value=\"" + value + "\" " + editable + "/>";
		} else {
			System.err.println("Type not recognized '" + fieldConfig.className + "'!");
		}
		return "";
	}
}
